using System;
using UnityEngine;
using QFramework;
using UnityEngine.Tilemaps;

namespace ProjectMyFarmAndShe
{
    public partial class GridController : ViewController,IController
    {
        public Tilemap GrassTilemap;
        public Tilemap WateringTilemap;
        public Tilemap DigTilemap;

        public TileBase WaterTilebase;
        public TileBase DigTilemapbase;

        private IGridSystem mSystem;
        
        //网格数据 用来存储植物数据 和状态的变更
        public DynaGrid<GridData> Grids;

        private void Awake()
        {
        }

        void LoadGridData()
        {
            var saveUtility = this.GetUtility<ISaveUtility>();
            
            var gridDatasKey = saveUtility.LoadString("GridDatas", string.Empty);

            if (string.IsNullOrEmpty(gridDatasKey))
            {
                
            }
            else
            {
                var saveGridData = JsonUtility.FromJson<SaveGridData>(gridDatasKey);

                foreach (var config in saveGridData.Datas)
                {
                    var gridData = new GridData();
                    gridData.SetWater(config.IsWater);
                    if (!string.IsNullOrEmpty(config.PlantItemKey))
                    {
                        var plantItem = GetPlantItemByItemKey(config.PlantItemKey);
                        plantItem.Position2D(new Vector2(config.X + 0.5f, config.Y + 0.5f))
                            .Show();
                        gridData.SetPlant(plantItem);

                        plantItem.CurrentPlantState = config.CurrentState;
                        plantItem.PlantIndex = config.PlantIndex;
                        plantItem.mPlantCount = config.PlantCount;
                    
                        plantItem.UpdatePlant();
                        plantItem.GridData = gridData;
                    }
                    
                    GrassTilemap.SetTile(new Vector3Int(config.X,config.Y), null);
                    DigTilemap.SetTile(new Vector3Int(config.X,config.Y), DigTilemapbase);

                    if (config.IsWater)
                    {
                        WateringTilemap.SetTile(new Vector3Int(config.X,config.Y), WaterTilebase);
                    }

                    Grids[config.X, config.Y] = gridData;
                }
            }
        }

        PlantItem GetPlantItemByItemKey(string key)
        {
            if (key == "蓝莓")
            {
                return Instantiate(ResController.Default.BlueBerryPlantItem);
            }
            else if (key == "茄子")
            {
                return Instantiate(ResController.Default.EggplantPlantItem);
            }
            else if (key == "葡萄")
            {
                return Instantiate(ResController.Default.GrapePlantItem);
            }
            else if (key == "粉红萝卜")
            {
                return Instantiate(ResController.Default.PinkRadishPlantItem);
            }
            else if (key == "土豆")
            {
                return Instantiate(ResController.Default.PotatoPlantItem);
            }
            else if (key == "萝卜")
            {
                return Instantiate(ResController.Default.TurnipPlantItem);
            }

            return null;
        }

        void Start()
        {
            mSystem = this.GetSystem<IGridSystem>();

            Grids = mSystem.Grids;

            LoadGridData();
            
            Global.Day.Register(day =>
                {
                    Global.Brawn.Value = Global.BrawnConfig;
                    
                    Grids.ForEach((x, y, gridData) =>
                    {
                        gridData.NextDay();

                        //天数改变 清除所有浇水的tile
                        WateringTilemap.ClearAllTiles();
                    });
                })
                .UnRegisterWhenGameObjectDestroyed(gameObject);
        }

        private bool CanUseTool = true;

        bool InRange(Vector3Int wordPos, Vector3Int playerPos, int range = 1)
        {
            var offsetX = -range;
            var offsetY = -range;

            for (var i = 0; i < 1 + 2 * range; i++)
            {
                for (var j = 0; j < 1 + 2 * range; j++)
                {
                    var cellX = offsetX + i;
                    var cellY = offsetY + j;

                    if (playerPos.x - wordPos.x == cellX && playerPos.y - wordPos.y == cellY)
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        private void Update()
        {
            var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            var wordPos = GrassTilemap.WorldToCell(mousePos);
            var playerPos = GrassTilemap.WorldToCell(Global.Player.Position2D());

            if (InRange(wordPos, playerPos, 3) && !Global.OpenPanel.Value)
            {
                Select.Show();
                Select.Position2D(new Vector2(wordPos.x + 0.5f, wordPos.y + 0.5f));

                if (Input.GetMouseButtonDown(0) && CanUseTool && !Global.OpenPanel.Value)
                {
                    //工具使用
                    if (Global.Tool != null && Global.Brawn.Value >= Global.Tool.UseBrawn)
                    {
                        CanUseTool = false;
                        
                        Global.Tool.Use(wordPos, Grids);
                        if (Global.Tool is HoeTool)
                        {
                            GrassTilemap.SetTile(wordPos, null);
                            DigTilemap.SetTile(wordPos, DigTilemapbase);
                            
                            CameraController.Default.Shake(0.1f, 0.1f);
                            ParticleFactory.Default.HoeFx.Instantiate()
                                .Self(self =>
                                {
                                    ActionKit.Delay(self.main.duration, () => { self.DestroyGameObjGracefully(); })
                                        .StartCurrentScene();
                                })
                                .Position2D(Select.Position2D())
                                .Show();
                        }
                        else if (Global.Tool is ShowerTool)
                        {
                            var grassTile = GrassTilemap.GetTile(wordPos);
                            if (grassTile == null)
                            {
                                WateringTilemap.SetTile(wordPos, WaterTilebase);
                            
                                ParticleFactory.Default.ShowerFx.Instantiate()
                                    .Self(self =>
                                    {
                                        ActionKit.Delay(self.main.duration, () => { self.DestroyGameObjGracefully(); })
                                            .StartCurrentScene();
                                    })
                                    .Position2D(Select.Position2D())
                                    .Show();
                            }
                        }
                        
                        ActionKit.Lerp(0, -360, 0.4f,
                                (z) =>
                                {
                                    Global.Mouse.ToolIcon.LocalRotation(Quaternion.Euler(0, 0, z)); 
                                    
                                }, () =>
                                {
                                    CanUseTool = true;
                                })
                            .StartCurrentScene();
                    }
                }
            }
            else
            {
                Select.Hide();
            }


            gameTime += Time.deltaTime;
        }
        private float gameTime;

        private void OnGUI()
        {
            GUI.Label(new Rect(50, 250, 200, 100), $"当前工具: {(Global.Tool != null ? Global.Tool.Name : "无")}",
                new GUIStyle()
                {
                    fontSize = 24,
                    fontStyle = FontStyle.Bold
                });

            GUI.Label(new Rect(50, 350, 200, 100), $"时间:{(int)gameTime}", new GUIStyle()
            {
                fontSize = 24,
                fontStyle = FontStyle.Bold
            });

            GUI.Label(new Rect(50, 450, 200, 100), $"按下ESC退出游戏", new GUIStyle()
            {
                fontSize = 24,
                fontStyle = FontStyle.Bold
            });

            GUI.Label(new Rect(50, 550, 200, 100), $"玩家触碰房子跳转下一天", new GUIStyle()
            {
                fontSize = 24,
                fontStyle = FontStyle.Bold
            });

            GUI.Label(new Rect(50, 650, 200, 100), $"右下角人物为商店", new GUIStyle()
            {
                fontSize = 24,
                fontStyle = FontStyle.Bold
            });

            GUI.Label(new Rect(50, 750, 200, 100), $"上方可以提交任务", new GUIStyle()
            {
                fontSize = 24,
                fontStyle = FontStyle.Bold
            });

            GUI.Label(new Rect(50, 850, 200, 100), $"商店会随机刷新种子,每五天刷新一次,每十天重置一次", new GUIStyle()
                {
                    fontSize = 24,
                    fontStyle = FontStyle.Bold
                });
        }

        public IArchitecture GetArchitecture()
        {
            return Global.Interface;
        }
    }
}